import { isEmpty, isNil, isObject, isString } from '@/common/helper/is'
import throttle from '@/common/helper/throttle'
import $store from '@/store'

const _go = (
  path,
  params = {},
  options = {
    redirect: false,
  },
) => {
  let page = '' // 跳转页面
  let query = {} // 页面参数
  let url = '' // 跳转页面完整路径

  if (isString(path)) {
    // 判断跳转类型是 path ｜ 还是http
    if (path.startsWith('http') || path.startsWith('www')) {
      // #ifdef H5
      window.location = path
      return
      // #endif
      // #ifndef H5
      page = '/pages/common/webview'
      query = { webviewPath: encodeURIComponent(path), ...params }
      // #endif
    } else if (path.startsWith('action:')) {
      handleAction(path)
      return
    } else {
      page = path.split('?')[0]
      query = getQueryVariable(path)
    }
    if (!isEmpty(params)) {
      query = { ...query, ...params }
    }
  }

  if (isObject(path)) {
    page = path.path.split('?')[0]
    query = getQueryVariable(path.path)
    if (!isNil(path.params)) {
      query = { ...query, ...path.params }
    }
  }

  const nextRoute = ROUTES_MAP[page]

  // 未找到指定跳转页面
  // mark: 跳转404页
  if (!nextRoute) {
    page = '/pages/common/404'
  }

  url = page
  if (!isEmpty(query)) {
    url += `?${paramsToQuery(query)}`
  }
  // console.log('🚀 ~ url:', url)

  // 路由pages.json->meta:{loginMode:'modal'}登录模式为'modal'时，以弹窗方式展示授权登录，否则以路由模式授权登录
  // 需登录页拦截
  if (nextRoute?.meta?.auth && !$store.getters.isLogin) {
    uni.$Auth({ route: { fullPath: url, ...nextRoute } })
    return
  }

  // 跳转底部导航
  if (TABBAR.includes(page)) {
    uni.switchTab({ url })
    return
  }

  // 使用redirect跳转
  if (options.redirect) {
    uni.redirectTo({ url })
    return
  }

  uni.navigateTo({ url })
}

// 限流 防止重复点击跳转
function go(...args) {
  throttle(() => {
    _go(...args)
  })
}

function back() {
  uni.navigateBack()
}

function redirect(path, params = {}) {
  go(path, params, {
    redirect: true,
  })
}

function goHome() {
  uni.reLaunch({ url: '/pages/main/home' })
}

// 检测是否有浏览器历史
function hasHistory() {
  const pages = getCurrentPages()
  if (pages.length > 1) return true

  return false
}

function getCurrentPage() {
  let pages = getCurrentPages()
  return pages[pages.length - 1]
}

function handleAction(path) {
  const action = path.split(':')
  switch (action[1]) {
    case 'showShareModal':
      showShareModal()
      break
  }
}

function paramsToQuery(params) {
  if (isEmpty(params)) {
    return ''
  }
  // return new URLSearchParams(Object.entries(params)).toString();
  let query = []
  for (let key in params) {
    query.push(key + '=' + params[key])
  }

  return query.join('&')
}

// 获取url参数对象
function getQueryVariable(url) {
  if (!url) return {}

  let t,
    n,
    r,
    i = url.split('?')[1],
    s = {}
  ;(t = i ? i.split('&') : []), (r = null), (n = null)
  for (var o in t) {
    const u = t[o].indexOf('=')
    u !== -1 && ((r = t[o].substr(0, u)), (n = t[o].substr(u + 1)), (s[r] = n))
  }
  return s
}

export default {
  go,
  back,
  hasHistory,
  redirect,
  goHome,
  getCurrentPage,
}
